﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;

namespace DusonFramework.Caching.DotNet
{
    /// <summary>
    /// In memory cache with no dependencies on the web cache, only runtime dependencies.
    /// ie. Can be used in any type of application,desktop,web,service or otherwise.
    /// </summary>
   public  class MemoryCacheAdapter : ICache
    {
       private MemoryCache _cache = MemoryCache.Default;

       /// <summary>
       /// 默认缓存存活期为3600秒(1小时)
       /// </summary>
       protected int _timeOut = 3600;

       public MemoryCacheAdapter() { }

       public void Add(string key, object value)
       {
           CacheItemPolicy policy = new CacheItemPolicy();
           policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(TimeOut));

           _cache.Add(key, value, policy);
       }

       public void AddWithFilesDepend(string key, object value, params string[] files)
       {
           CacheItemPolicy policy = new CacheItemPolicy();
           policy.ChangeMonitors.Add(new HostFileChangeMonitor(files));

           _cache.Add(key, value, policy);
       }

       public void AddWithCacheItemsDepend(string key, object value, params string[] dependKey)
       {
           CacheItemPolicy policy = new CacheItemPolicy();
           policy.ChangeMonitors.Add(_cache.CreateCacheEntryChangeMonitor(dependKey));

           _cache.Add(key, value, policy);
       }

       public void Remove(string key)
       {
           _cache.Remove(key);
       }

       public bool Contains(string key)
       {
           return _cache.Contains(key);
       }

       public object Get(string key)
       {
           return _cache.Get(key);
       }

       /// <summary>
       /// 设置到期相对时间[单位: 秒] 
       /// </summary>
       public virtual int TimeOut
       {
           set { _timeOut = value > 0 ? value : 3600; }
           get { return _timeOut > 0 ? _timeOut : 3600; }
       }
    
   }
}
